package net.vmiranda.jeds.web.util;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;

import net.vmiranda.jeds.utils.modulos.Modulo;
import net.vmiranda.jeds.web.tareas.MBTarea;

public class JedsPhaseListener implements PhaseListener {

	

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("deprecation")
	public void afterPhase(PhaseEvent phaseEvent) {
		 FacesContext facesContext = phaseEvent.getFacesContext();
		 String viewId = phaseEvent.getFacesContext().getViewRoot().getViewId();
		 String s=((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("nuevoModulo").toString();  
		 //System.out.println(viewId);
		 if (viewId.endsWith(".xhtml")&& s.equals("si")) {
		      String managedBeanName = getManagedBeanNameFromView(viewId);
		      System.out.println(managedBeanName);
		      //System.err.println(managedBeanName);
		      Modulo object = (Modulo) facesContext.getApplication().createValueBinding("#{" + managedBeanName + "}").getValue(facesContext);
		      if (object == null);
		        //System.out.println("OnPageLoad cannot be executed, no such managed bean:"+ managedBeanName);
		      else {
		    	  object.entrarEnInsercion();
		    	  
		    	  
		    	  //ILifeCycleAware lifeCycleAwareBean = (ILifeCycleAware) object;
		        //lifeCycleAwareBean.onPageLoad();
		      }
		    }

	}

	
	public void beforePhase(PhaseEvent arg0) {

		//System.out.println("Antes de "+arg0.getPhaseId());

	}

	
	public PhaseId getPhaseId() {
		// TODO Auto-generated method stub
		return PhaseId.ANY_PHASE;
	}

	public String getManagedBeanNameFromView(String viewId) {
	    String pageName = viewId.substring(1, viewId.length() - 7);
	    String partes[] = pageName.split("/");
	    int numPartes = partes.length;
	    String s = partes[numPartes-1];
	    return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
	  }
}
